package cn.careerx.app.common.models;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.SqlRow;

import redis.clients.jedis.Jedis;

public class Occupation implements Serializable{

	private static final long serialVersionUID = -1732142518627484049L;

	private String id;
	private String name;
	private Integer levelCount;
	private String advice;
	private String levelJson;
	
	//Redis keys
	private static final String OCCNFO_KEY="occupationInfo:";
	
	public static Occupation create(){
		return new Occupation();
	}
	
	public static Occupation getOccById(Database db,Jedis jedis,String id){
		String key = OCCNFO_KEY+id;
		Occupation result = null;
		Map<String,String> resultMap = null;
		String keyId = "id",keyName="name",keyLevelCount="levelCount",keyAdvice="advice",keyLevelJson="levelJson";
		if(jedis.exists(key)){
			resultMap = jedis.hgetAll(key);
		}else{
			EbeanServer es = db.getDbByPartitionKey("CAREERX", "");
			SqlRow row = es.createSqlQuery("SELECT * FROM CX_OCCUPATION WHERE ID=?").setParameter(1, id).findUnique();
			if(row == null){
				return null;
			}
			resultMap = new HashMap<String,String>();
			resultMap.put(keyId, row.getString("ID"));
			resultMap.put(keyName, dealNull(row.getString("NAME")));
			resultMap.put(keyLevelCount, dealNull(row.getInteger("LEVEL_COUNT")));
			resultMap.put(keyAdvice, dealNull(row.getString("ADVICE")));
			resultMap.put(keyLevelJson,dealNull(row.getString("LEVEL_JSON")));
			jedis.hmset(key, resultMap);
		}
		result = Occupation.create()
				   .setId(resultMap.get(keyId))
				   .setName(resultMap.get(keyName))
				   .setLevelCount(Integer.parseInt(resultMap.get(keyLevelCount)))
				   .setAdvice(resultMap.get(keyAdvice))
				   .setLevelJson(resultMap.get(keyLevelJson));
		return result;
	}
	
	private static String dealNull(String str){
		return str==null?"":str;
	}
	
	private static String dealNull(Integer str){
		return str==null?"0":String.valueOf(str);
	}
	
	/***************************Setter and getters******************************************/
	public String getId() {
		return id == null ? "" : id;
	}
	public Occupation setId(String id) {
		this.id = id;
		return this;
	}
	public String getName() {
		return name == null ? "" : name;
	}

	public Occupation setName(String name) {
		this.name = name;
		return this;
	}

	public Integer getLevelCount() {
		return levelCount == null ? 0 : levelCount;
	}

	public Occupation setLevelCount(Integer levelCount) {
		this.levelCount = levelCount;
		return this;
	}

	public String getAdvice() {
		return advice == null ? "" : advice;
	}

	public Occupation setAdvice(String advice) {
		this.advice = advice;
		return this;
	}

	public String getLevelJson() {
		return levelJson == null ? "" : levelJson;
	}

	public Occupation setLevelJson(String levelJson) {
		this.levelJson = levelJson;
		return this;
	}

	
}
